package StudyCode.summary.zipfile;

import java.io.*;
import java.util.zip.GZIPInputStream;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class DecompressByteArrayGZIP {
	public static String decompress(byte[] compressed) throws IOException {
		byte[] h = new byte[2];
		h[0] = (compressed)[0];
		h[1] = (compressed)[1];
		int head = getShort(h);
		boolean t = head == 0x1f8b;
		InputStream in = null;
		StringBuilder sb = new StringBuilder();
		try {
			ByteArrayInputStream bis = new ByteArrayInputStream(compressed);
			if (t) {
				in = new GZIPInputStream(bis);
			} else {
				in = bis;
			}
			BufferedReader r = new BufferedReader(
					new InputStreamReader(in), 1000);
			for (String line = r.readLine(); line != null; line = r
					.readLine()) {
				sb.append(line);
			}
			r.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (in != null) {
				in.close();
			}
		}
		return sb.toString();
	}

	private static int getShort(byte[] data) {
		return (int) ((data[0] << 8) | data[1] & 0xFF);
	}
}
